/** 
 * <p>Original Author:  jessefreeman</p>
 * <p>Class File: WindowStackLayout.as
 * 
 * <p>Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:</p>
 * 
 * <p>The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.</p>
 * 
 * <p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.</p>
 * 
 * <p>Licensed under The MIT License</p>
 * <p>Redistributions of files must retain the above copyright notice.</p>
 *
 * <p>Revisions<br/> 
 * 	0.1  Initial version Oct 6, 2008</p>
 *
 */
 
package camo.views.components.layouts
{

	import camo.debug.DumpUtility;
	import camo.events.ComponentEvent;
	import camo.models.CamoModel;
	import camo.models.IModel;
	import camo.views.components.AbstractComponent;
	import camo.views.components.buttons.TextToggleButton;
	import camo.views.components.fields.IField;
	import camo.views.components.fields.LabelField;
	
	import flash.errors.IllegalOperationError;
	import flash.events.EventDispatcher;

	public class ColumnLayout extends TileLayout
	{
		public static const LABEL:String = "label";
		public static const WIDTH:String = "width";
		public static const SORTABLE:String = "sortable";
		public static const STYLE_ID:String = "styleID";
		
		protected var _columns:Array;
		protected var _columnLabels:Array;
		protected var _labelLayout:TileLayout;
		protected var _columnXCoords:Array;
		protected var _showColumnLabels:Boolean = true;
		
		protected var _tabularData:Array;
		
		/**
		 * 
		 */
		public function get labels():Array{
			return _columnLabels;
		}
		
		/**
		 * 
		 * @param id
		 * @return 
		 * 
		 */		
		public function getRawData(id:String):Object{
			return new Object();
		}
		
		/**
		 * Creates a layout container for column labels.
		 */
		public function set labels(value:Array):void{
			_columnLabels = value;
			var labelLayoutConfig:CamoModel = new CamoModel();
				labelLayoutConfig.id = id+"LabelLayout";
				labelLayoutConfig.direction = "horizontal";
				
			var labelItems:Array = new Array();
			var totalLabels:Number = _columnLabels.length;
			
			for (var i:int = 0; i < totalLabels; i++){
				labelItems.push(createColumnLabel("label"+i+"_"+_columnLabels[i].label,_columnLabels[i]));
			} 	
			
			_labelLayout = new TileLayout(labelLayoutConfig);
			_labelLayout.draw(labelItems);
			
			
			addSortListeners(_labelLayout);
			
		}
		
		
		/**
		 * 
		 */
		public function set tabularData(value:Array):void{
			
			_tabularData = value;
			
			// Create holder array for columns as they are created
			var columnLayouts:Array = new Array();
			
			columnLayouts.push(_labelLayout);
			
			// Create Column Content
			var totalRows:Number = _tabularData.length;
			
			for (var i:int = 0; i < totalRows; i++){
				
				var tData:Object = _tabularData[i];
				
				var rowName:String = (tData.id) ? tData.id : "row"+i;
				var tempRow:Layout = createRow(rowName,tData);
				columnLayouts.push(tempRow);
								
				tData.instance = tempRow;
			}
			
			draw(columnLayouts);
		}
	
		
		public function get tabularData():Array{
			return _tabularData;
		}
		
		public function getColumnLabel(id:Number):String{
			return _columns[id];
		}
		
		/**
		 * 
		 */
		public function ColumnLayout(model:IModel = null)
		{
			super(model);
		}
		
		/**
		 * 
		 */
		override protected function init(model:IModel):void{
			super.init(model);
		}
		
		/**
		 * Specialized draw function that creates a labels layout then renders
		 * items into columns, finally passing the columns up to the super to be
		 * created.
		 */
		override public function draw(items:Array):void{

			if(!_columnLabels){
				throw new IllegalOperationError("ColumnLayout '"+id+"' does not have a label array. Please supply one before trying to draw the Table.");
				return;
			}
			
			// Pass column layouts up to the super's draw function
			super.draw(items);
			
		}

		/**
		 * 
		 */
		override protected function getItem(id:Number):AbstractComponent{
			return instances[id];
		}
		
		/**
		 * 
		 */
		protected function createColumnLabel(id:String, data:Object):IField{
			var width:Number = data[WIDTH];
			var sortable:String = data[SORTABLE];

			var config:CamoModel = new CamoModel();
				config.id = id;
				config.styleID = data[STYLE_ID];
				
			var tempLabel:IField
				
			if(sortable){
				// Create TextToggleButton
				tempLabel = createToggleButton(config);
				tempLabel["action"] = "sort";
			}else{
				// Create LabelField
				tempLabel= new LabelField(config);
			}
			
			tempLabel.text = data[LABEL];
			
			return tempLabel;
		}
		
		/**
		 * 
		 * @param config
		 * 
		 */		
		protected function createToggleButton(config:IModel):TextToggleButton{
			return new TextToggleButton(config);
		}
		
		/**
		 * 
		 * @param config
		 * @return 
		 * 
		 */		
		protected function createRowContainer(config:IModel):Layout{
			return new TileLayout(config);
		}
		
		protected function createRow(id:String, data:Object):Layout{
			
			var config:CamoModel = new CamoModel();
				config.name = id;
				config.id = "JobRowLayout";
				config.direction = "horizontal";
				
			var tempLayout:Layout = createRowContainer(config);
				
			var items:Array = new Array();

			var total:Number = _columnLabels.length;
			var label:String;
			
			for(var i:int; i < total; i++) {
				
				label = _columnLabels[i][LABEL];
				
				if(data[label]){
					
					var cellConfig:CamoModel = new CamoModel();
						cellConfig.id = label+"Cell";
					var tempLabel:LabelField = new LabelField(cellConfig);
						tempLabel.text = data[label];
					items.push(tempLabel);	
				}
			}
			
			tempLayout.action = "selected";
			tempLayout.activate = true;
			tempLayout.draw(items);
			
			return tempLayout;
		}
		
		/**
		 * 
		 */
		protected function addSortListeners(target:EventDispatcher):void{
			target.addEventListener(ComponentEvent.TOGGLE_CHANGE, onSortAction);
		}
		
		/**
		 * 
		 */
		protected function removeSortListeners(target:EventDispatcher):void{
			target.removeEventListener(ComponentEvent.TOGGLE_CHANGE, onSortAction);
		}
		
		/**
		 * 
		 */
		protected function onSortAction(e:ComponentEvent):void{
			e.stopImmediatePropagation();
			if(e.data.action == "sort"){
				
				var field:String = e.target.id.split("_")[1];
				
				var order:uint = (!e.data.value) ? Array.DESCENDING : null;
				_tabularData.sortOn(field,order);

				clear();
				tabularData = _tabularData;
				
			}
		}
		
		protected function reorderInstances():void{	
			
			instances = new Array();
			
			var total:int = _tabularData.length;
			
			for (var i:int = 0; i < total; i++){
				
				
			}

		}
		
		
		public function refreshTable():void{
			
			
		}
		
		/* 
		protected function onToggleChange(e:ComponentEvent):void{
			trace("New ToggleChange: "+e);
		} */
		
		/**
		 * Outputs the current tabularData. Use this for testing sorting.
		 */
		public function dump():void{
			
			var total:Number = _tabularData.length;
			
			for (var i:int = 0; i < total; i++){
				
				DumpUtility.dumpThis(_tabularData[i],"Row "+i);
			}
			
		}
	}
}